import { Client } from "../client/Client";
import { GuildMemberUserDto, GuildMemberDto } from "./dto/GuildMember";
import { Guild } from "./Guild";
import { Snowflake } from "./utils/Snowflake";


export class GuildMemberUser {

    id!: Snowflake
    username!: string
    global_name!: string
    display_name!: string
    bot!: boolean
    discriminator!: string
    avatar?: string

    constructor(private client: Client, dto: GuildMemberUserDto) {
        this._patch(dto);
    }

    _patch(data: GuildMemberUserDto) {

        // console.log("GuildMemberUser " + JSON.stringify(data) )

        this.id = data.id
        this.username = data.username
        this.global_name = data.global_name 
        this.display_name = data.display_name
        this.bot = data.bot
        this.discriminator = data.discriminator
        this.avatar = data.avatar
    }
}

export class GuildMember {
    user!: GuildMemberUser
    roles: string[] = []

    constructor(private client: Client, private guild: Guild, dto: GuildMemberDto) {
        this._patch(dto);
    }

    _patch(data: GuildMemberDto) {

        // console.log("GuildMember " + JSON.stringify(data) )

        this.user = new GuildMemberUser(this.client, data.user);
        this.roles = data.roles
    }

    get id() {
        return this.user.id;
    }
 
    get getColor() {

        let numberColor = 0;
        const newList = [...this.roles]

        newList.sort((a,b)=>{
            return this.guild.roles[b].position - this.guild.roles[a].position
        })


        for (let index = 0; index < newList.length; index++) {
            const roleId = newList[index];
        
            if (this.guild.roles[roleId].color > 0) {
                numberColor = this.guild.roles[roleId].color
                break
            }
        }


        return (numberColor).toString(16)
    }

    get avatarURL() {
        return this.user.avatar 
        ? "https://cdn.discordapp.com/avatars/" +  this.user.id + "/" + this.user.avatar + ".png"
        : "https://cdn.discordapp.com/embed/avatars/" + (+this.user.discriminator % 5) + ".png"
    }
}
